package com.getan.boot.jdbc.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.getan.boot.common.holder.security.SecurityContextHolder;
import com.getan.boot.common.holder.trace.TraceContextHolder;
import com.getan.boot.common.utils.DateUtils;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;

/**
 * 自动填充接口
 * 如果数据库有该字段，则会自动填充，如果没有，则会跳过，所以即便对象不是继承 {@code GenericEntity}，也是可以使用的。
 *
 * @author Bruce.Gong
 * @see com.getan.boot.jdbc.entity.GenericEntity
 * @since 1.0.0-SNAPSHOT
 */
public class GetanMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        LocalDateTime now = DateUtils.now();
        this.strictInsertFill(metaObject, "deleted", () -> false, Boolean.class);
        this.strictInsertFill(metaObject, "createTime", () -> now, LocalDateTime.class);
        this.strictInsertFill(metaObject, "createBy", SecurityContextHolder::getCurrentUserName, String.class);
        this.strictInsertFill(metaObject, "updateTime", () -> now, LocalDateTime.class);
        this.strictInsertFill(metaObject, "updateBy", SecurityContextHolder::getCurrentUserName, String.class);
        this.strictInsertFill(metaObject, "traceId", TraceContextHolder::getTraceId, String.class);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime", DateUtils::now, LocalDateTime.class);
        this.strictUpdateFill(metaObject, "updateBy", SecurityContextHolder::getCurrentUserName, String.class);
        this.strictInsertFill(metaObject, "traceId", TraceContextHolder::getTraceId, String.class);
    }

}
